#include "RingQueue.hpp"

class ThreadData
{
public:
    RingQueue<Task> * rq;
    std::string threadname;
};

void* Productor(void *args)
{
    //RingQueue<Task> *rq=static_cast<RingQueue<Task> *>(args);
    ThreadData *td=static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name=td->threadname;
    int len=opers.size();
    while (true)
    {
        //1.获取数据
        int data1 = rand()%10+1;
        usleep(10);
        int data2 = rand()%10;
        char op=opers[rand()%len];
        Task task(data1,data2,op);
        //2.生产数据
        rq->Push(task);
        std::cout<<"Productor Task done,Task is: "<< task.GetTask() <<",who: "<<name <<std::endl;
        sleep(1);
    }
    return nullptr;
}

void* Consumer(void *args)
{
    //RingQueue<Task> *rq=static_cast<RingQueue<Task> *>(args);
    ThreadData *td=static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name=td->threadname;
    while (true)
    {
        //1.消费数据 
        Task task;
        rq->Pop(&task);
        //2.处理数据
        task();
        std::cout<<"Consumer get Task,Task is: "<< task.GetTask() <<", Result: "<<task.GetResult()<<",who: "<<name<<std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr)^getpid());
    RingQueue<Task> *rq=new RingQueue<Task>(50);
    pthread_t c[5],p[3];

    for(int i=0;i<1;i++) {
        ThreadData *td=new ThreadData();
        td->rq=rq;
        td->threadname="Consumer-"+std::to_string(i);
        pthread_create(c+i,nullptr,Consumer,td);
    }
    for(int i=0;i<1;i++) {
        ThreadData *td=new ThreadData();
        td->rq=rq;
        td->threadname="Productor-"+std::to_string(i);
        pthread_create(p+i,nullptr,Productor,td);
    }

    for(int i=0;i<1;i++) { pthread_join(c[i],nullptr); }
    for(int i=0;i<1;i++) { pthread_join(p[i],nullptr); }

    // pthread_create(&c,nullptr,Consumer,rq);
    // pthread_create(&p,nullptr,Productor,rq);

    // pthread_join(c,nullptr);
    // pthread_join(p,nullptr);

    return 0;
}